<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>自制深度学习框架--再探Tensor类并构建计算图的图关系 | kiloGrand</title><meta name="keywords" content="kuiper_infer"><meta name="author" content="kiloGrand"><meta name="copyright" content="kiloGrand"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="再探Tensor类在之前，我们实现的张量初始化是这样的。123Tensor&lt;float&gt;::Tensor(uint32_t channels, uint32_t rows, uint32_t cols) &amp;#123;  data_ &#x3D; arma::fcube(rows, cols, channels);&amp;#125;这个Tensor类其实并不能满足我们的使用需要，因为我们有些时候数据并不">
<meta property="og:type" content="article">
<meta property="og:title" content="自制深度学习框架--再探Tensor类并构建计算图的图关系">
<meta property="og:url" content="https://kilogrand.gitee.io/2023/03/21/kuiper_infer-L11/index.html">
<meta property="og:site_name" content="kiloGrand">
<meta property="og:description" content="再探Tensor类在之前，我们实现的张量初始化是这样的。123Tensor&lt;float&gt;::Tensor(uint32_t channels, uint32_t rows, uint32_t cols) &amp;#123;  data_ &#x3D; arma::fcube(rows, cols, channels);&amp;#125;这个Tensor类其实并不能满足我们的使用需要，因为我们有些时候数据并不">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://kilogrand.gitee.io/img/coding.jpg">
<meta property="article:published_time" content="2023-03-21T12:00:00.000Z">
<meta property="article:modified_time" content="2023-04-20T15:05:33.058Z">
<meta property="article:author" content="kiloGrand">
<meta property="article:tag" content="kuiper_infer">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://kilogrand.gitee.io/img/coding.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://kilogrand.gitee.io/2023/03/21/kuiper_infer-L11/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '自制深度学习框架--再探Tensor类并构建计算图的图关系',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-04-20 23:05:33'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/profile.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/coding.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">kiloGrand</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">自制深度学习框架--再探Tensor类并构建计算图的图关系</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-03-21T12:00:00.000Z" title="发表于 2023-03-21 20:00:00">2023-03-21</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-04-20T15:05:33.058Z" title="更新于 2023-04-20 23:05:33">2023-04-20</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/">深度学习</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>12分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="自制深度学习框架--再探Tensor类并构建计算图的图关系"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="再探Tensor类"><a href="#再探Tensor类" class="headerlink" title="再探Tensor类"></a>再探Tensor类</h2><p>在之前，我们实现的张量初始化是这样的。<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Tensor&lt;<span class="type">float</span>&gt;::<span class="built_in">Tensor</span>(<span class="type">uint32_t</span> channels, <span class="type">uint32_t</span> rows, <span class="type">uint32_t</span> cols) &#123;</span><br><span class="line">  data_ = arma::<span class="built_in">fcube</span>(rows, cols, channels);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><br>这个<code>Tensor</code>类其实并不能满足我们的使用需要，因为我们有些时候数据并不是三维的，<br>原来的Tensor不能在逻辑上区分当前的张量是三维的、二维的还是一维的，因为实际的数据存储类arma::fcube总是一个三维数据。<br>而且在之前我们也没有实现reshape。</p>
<p>所以，现在让我们一起来完善这个<code>Tensor</code>类吧。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">Tensor&lt;<span class="type">float</span>&gt;::<span class="built_in">Tensor</span>(<span class="type">uint32_t</span> channels, <span class="type">uint32_t</span> rows, <span class="type">uint32_t</span> cols) &#123;</span><br><span class="line">  <span class="comment">// float cube(n_rows, n_cols, n_slices)</span></span><br><span class="line">  data_ = arma::<span class="built_in">fcube</span>(rows, cols, channels);</span><br><span class="line">  <span class="keyword">if</span> (channels == <span class="number">1</span> &amp;&amp; rows == <span class="number">1</span>) &#123;</span><br><span class="line">    <span class="keyword">this</span>-&gt;raw_shapes_ = std::vector&lt;<span class="type">uint32_t</span>&gt;&#123;cols&#125;;</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (channels == <span class="number">1</span>) &#123;</span><br><span class="line">    <span class="keyword">this</span>-&gt;raw_shapes_ = std::vector&lt;<span class="type">uint32_t</span>&gt;&#123;rows, cols&#125;;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">this</span>-&gt;raw_shapes_ = std::vector&lt;<span class="type">uint32_t</span>&gt;&#123;channels, rows, cols&#125;;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在这里，我们调用<a target="_blank" rel="noopener" href="https://arma.sourceforge.net/docs.html#Cube">arma::fcube</a>来初始化data<em>，<br>同时<code>raw_shape</code>记录的是另外一个方面的形状信息，主要用于review和flatten层中。<br>尽管实际的数据存储类arma::fcube总是一个三维数据，但是逻辑上用raw_shapes</em>来记录当前的张量是三维的、二维的还是一维的。</p>
<h3 id="列优先的Reshape"><a href="#列优先的Reshape" class="headerlink" title="列优先的Reshape"></a>列优先的Reshape</h3><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> Tensor&lt;<span class="type">float</span>&gt;::<span class="built_in">ReRawshape</span>(<span class="type">const</span> std::vector&lt;<span class="type">uint32_t</span>&gt;&amp; shapes) &#123;</span><br><span class="line">  <span class="built_in">CHECK</span>(!<span class="keyword">this</span>-&gt;data_.<span class="built_in">empty</span>());</span><br><span class="line">  <span class="built_in">CHECK</span>(!shapes.<span class="built_in">empty</span>());</span><br><span class="line">  <span class="type">const</span> <span class="type">uint32_t</span> origin_size = <span class="keyword">this</span>-&gt;<span class="built_in">size</span>();</span><br><span class="line">  <span class="type">uint32_t</span> current_size = <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">for</span> (<span class="type">uint32_t</span> s : shapes) &#123;</span><br><span class="line">    current_size *= s;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">CHECK</span>(shapes.<span class="built_in">size</span>() &lt;= <span class="number">3</span>);</span><br><span class="line">  <span class="built_in">CHECK</span>(current_size == origin_size);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// cube.reshape( n_rows, n_cols, n_slices )</span></span><br><span class="line">  <span class="keyword">if</span> (shapes.<span class="built_in">size</span>() == <span class="number">3</span>) &#123;</span><br><span class="line">    <span class="comment">// shapes = &#123;channels, rows, cols&#125;</span></span><br><span class="line">    <span class="keyword">this</span>-&gt;data_.<span class="built_in">reshape</span>(shapes.<span class="built_in">at</span>(<span class="number">1</span>), shapes.<span class="built_in">at</span>(<span class="number">2</span>), shapes.<span class="built_in">at</span>(<span class="number">0</span>));</span><br><span class="line">    <span class="keyword">this</span>-&gt;raw_shapes_ = &#123;shapes.<span class="built_in">at</span>(<span class="number">0</span>), shapes.<span class="built_in">at</span>(<span class="number">1</span>), shapes.<span class="built_in">at</span>(<span class="number">2</span>)&#125;;</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (shapes.<span class="built_in">size</span>() == <span class="number">2</span>) &#123;</span><br><span class="line">    <span class="comment">// shapes = &#123;rows, cols&#125;</span></span><br><span class="line">    <span class="keyword">this</span>-&gt;data_.<span class="built_in">reshape</span>(shapes.<span class="built_in">at</span>(<span class="number">0</span>), shapes.<span class="built_in">at</span>(<span class="number">1</span>), <span class="number">1</span>);</span><br><span class="line">    <span class="keyword">this</span>-&gt;raw_shapes_ = &#123;shapes.<span class="built_in">at</span>(<span class="number">0</span>), shapes.<span class="built_in">at</span>(<span class="number">1</span>)&#125;;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// shapes = &#123;cols&#125;</span></span><br><span class="line">    <span class="keyword">this</span>-&gt;data_.<span class="built_in">reshape</span>(shapes.<span class="built_in">at</span>(<span class="number">0</span>), <span class="number">1</span>, <span class="number">1</span>);</span><br><span class="line">    <span class="keyword">this</span>-&gt;raw_shapes_ = &#123;shapes.<span class="built_in">at</span>(<span class="number">0</span>)&#125;;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在这里调用了<a target="_blank" rel="noopener" href="https://arma.sourceforge.net/docs.html#reshape_member">armadillo::cube.reshape</a>，<br>由于<code>armadillo::cube</code>是一个列优先的容器，所以<code>Reshape</code>的方式是列优先的。</p>
<h3 id="行优先的Reshape"><a href="#行优先的Reshape" class="headerlink" title="行优先的Reshape"></a>行优先的Reshape</h3><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> Tensor&lt;<span class="type">float</span>&gt;::<span class="built_in">ReView</span>(<span class="type">const</span> std::vector&lt;<span class="type">uint32_t</span>&gt;&amp; shapes) &#123;</span><br><span class="line">  <span class="built_in">CHECK</span>(!<span class="keyword">this</span>-&gt;data_.<span class="built_in">empty</span>());</span><br><span class="line">  <span class="comment">// shapes = &#123;channels, rows, cols&#125;</span></span><br><span class="line">  <span class="type">const</span> <span class="type">uint32_t</span> target_channels = shapes.<span class="built_in">at</span>(<span class="number">0</span>);</span><br><span class="line">  <span class="type">const</span> <span class="type">uint32_t</span> target_rows = shapes.<span class="built_in">at</span>(<span class="number">1</span>);</span><br><span class="line">  <span class="type">const</span> <span class="type">uint32_t</span> target_cols = shapes.<span class="built_in">at</span>(<span class="number">2</span>);</span><br><span class="line">  <span class="comment">// 初始化new_data用于存放reshape后的结果</span></span><br><span class="line">  <span class="function">arma::fcube <span class="title">new_data</span><span class="params">(target_rows, target_cols, target_channels)</span></span>;</span><br><span class="line"></span><br><span class="line">  <span class="type">const</span> <span class="type">uint32_t</span> plane_size = target_rows * target_cols;</span><br><span class="line">  <span class="keyword">for</span> (<span class="type">uint32_t</span> c = <span class="number">0</span>; c &lt; <span class="keyword">this</span>-&gt;data_.n_slices; ++c) &#123;</span><br><span class="line">    <span class="comment">// 逐通道遍历，取出每一通道的数据</span></span><br><span class="line">    <span class="type">const</span> arma::fmat&amp; channel = <span class="keyword">this</span>-&gt;data_.<span class="built_in">slice</span>(c);</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">uint32_t</span> c_ = <span class="number">0</span>; c_ &lt; <span class="keyword">this</span>-&gt;data_.n_cols; ++c_) &#123;</span><br><span class="line">      <span class="comment">// 逐列遍历</span></span><br><span class="line">      <span class="type">const</span> <span class="type">float</span>* colptr = channel.<span class="built_in">colptr</span>(c_);</span><br><span class="line">      <span class="keyword">for</span> (<span class="type">uint32_t</span> r = <span class="number">0</span>; r &lt; <span class="keyword">this</span>-&gt;data_.n_rows; ++r) &#123;</span><br><span class="line">        <span class="comment">// 逐行遍历</span></span><br><span class="line">        <span class="comment">// 当前元素的位置=c*通道+r*列+c_*行</span></span><br><span class="line">        <span class="type">const</span> <span class="type">uint32_t</span> pos_index =</span><br><span class="line">            c * data_.n_rows * data_.n_cols + r * data_.n_cols + c_;</span><br><span class="line">        <span class="comment">// 计算reshape后的位置</span></span><br><span class="line">        <span class="type">const</span> <span class="type">uint32_t</span> ch = pos_index / plane_size;</span><br><span class="line">        <span class="type">const</span> <span class="type">uint32_t</span> row = (pos_index - ch * plane_size) / target_cols;</span><br><span class="line">        <span class="type">const</span> <span class="type">uint32_t</span> col = (pos_index - ch * plane_size - row * target_cols);</span><br><span class="line">        <span class="comment">// 拷贝</span></span><br><span class="line">        new_data.<span class="built_in">at</span>(row, col, ch) = *(colptr + r);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>-&gt;data_ = new_data;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="构建计算图的图关系"><a href="#构建计算图的图关系" class="headerlink" title="构建计算图的图关系"></a>构建计算图的图关系</h2><p>在之前的计算图初始化中<code>RuntimeGraph::Init()</code>，我们并没有构建计算图的图关系。<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 构建图关系</span></span><br><span class="line"><span class="keyword">for</span> (<span class="type">const</span> <span class="keyword">auto</span> &amp;current_op : <span class="keyword">this</span>-&gt;operators_) &#123;</span><br><span class="line">  <span class="comment">// 当前算子的后一层算子的名字</span></span><br><span class="line">  <span class="type">const</span> std::vector&lt;std::string&gt; &amp;output_names = current_op-&gt;output_names;</span><br><span class="line">  <span class="comment">// 遍历operators_</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="type">const</span> <span class="keyword">auto</span> &amp;next_op : <span class="keyword">this</span>-&gt;operators_) &#123;</span><br><span class="line">    <span class="comment">// 如果遍历到当前节点，跳到下一轮</span></span><br><span class="line">    <span class="keyword">if</span> (next_op == current_op) &#123;</span><br><span class="line">      <span class="keyword">continue</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 如果遇到next_op的name和当前current_op-&gt;output_name是一致的</span></span><br><span class="line">    <span class="keyword">if</span> (std::<span class="built_in">find</span>(output_names.<span class="built_in">begin</span>(), output_names.<span class="built_in">end</span>(), next_op-&gt;name) !=</span><br><span class="line">        output_names.<span class="built_in">end</span>()) &#123;</span><br><span class="line">      <span class="comment">// 将next_op插入到current_op的下一个节点当中</span></span><br><span class="line">      current_op-&gt;output_operators.<span class="built_in">insert</span>(&#123;next_op-&gt;name, next_op&#125;);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>计算图初始化完成后，接下来我们需要做的事情是<strong>找到op list(this-&gt;operators)中的输入和输出节点</strong><br>总所周知，一个图一定有一个输入和输出。打个比方，<br>图的执行好像在走迷宫，就好像我们走迷宫之前需要先指定迷宫的输入输出位置。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">RuntimeGraph::Build</span><span class="params">(<span class="type">const</span> std::string &amp;input_name, <span class="type">const</span> std::string &amp;output_name)</span> </span>&#123;</span><br><span class="line">  <span class="comment">// 如何计算图没有初始化，就初始化</span></span><br><span class="line">  <span class="keyword">if</span> (graph_state_ == GraphState::NeedInit) &#123;</span><br><span class="line">    <span class="type">bool</span> init_graph = <span class="built_in">Init</span>();</span><br><span class="line">    <span class="built_in">LOG_IF</span>(FATAL, !init_graph) &lt;&lt; <span class="string">&quot;Init graph failed!&quot;</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">CHECK</span>(graph_state_ &gt;= GraphState::NeedBuild)</span><br><span class="line">          &lt;&lt; <span class="string">&quot;Graph status error, current state is &quot;</span> &lt;&lt; <span class="built_in">int</span>(graph_state_);</span><br><span class="line">  <span class="built_in">LOG_IF</span>(FATAL, <span class="keyword">this</span>-&gt;operators_.<span class="built_in">empty</span>())</span><br><span class="line">          &lt;&lt; <span class="string">&quot;Graph operators is empty, may be no init&quot;</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>-&gt;input_operators_maps_.<span class="built_in">clear</span>();</span><br><span class="line">  <span class="keyword">this</span>-&gt;output_operators_maps_.<span class="built_in">clear</span>();</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 遍历operators</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="type">const</span> <span class="keyword">auto</span> &amp;kOperator : <span class="keyword">this</span>-&gt;operators_) &#123;</span><br><span class="line">    <span class="keyword">if</span> (kOperator-&gt;type == <span class="string">&quot;pnnx.Input&quot;</span>) &#123;</span><br><span class="line">      <span class="comment">// 找到this-&gt;operators中的输入节点</span></span><br><span class="line">      <span class="keyword">this</span>-&gt;input_operators_maps_.<span class="built_in">insert</span>(&#123;kOperator-&gt;name, kOperator&#125;);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (kOperator-&gt;type == <span class="string">&quot;pnnx.Output&quot;</span>) &#123;</span><br><span class="line">      <span class="comment">// 找到this-&gt;operators中的输出节点，目前只是支持一个输出</span></span><br><span class="line">      <span class="keyword">this</span>-&gt;output_operators_maps_.<span class="built_in">insert</span>(&#123;kOperator-&gt;name, kOperator&#125;);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// 以后的课中加layer的</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 初始化每个算子的输入和输出空间</span></span><br><span class="line">  RuntimeGraphShape::<span class="built_in">InitOperatorInputTensor</span>(operators_);</span><br><span class="line">  RuntimeGraphShape::<span class="built_in">InitOperatorOutputTensor</span>(graph_-&gt;ops, operators_);</span><br><span class="line">  graph_state_ = GraphState::Complete;</span><br><span class="line">  input_name_ = input_name;</span><br><span class="line">  output_name_ = output_name;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="初始化各算子的输入和输出空间"><a href="#初始化各算子的输入和输出空间" class="headerlink" title="初始化各算子的输入和输出空间"></a>初始化各算子的输入和输出空间</h2><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">RuntimeGraphShape</span> &#123;</span><br><span class="line"> <span class="keyword">public</span>:</span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 如果图是第一次运行，则根据节点输入operand的形状准备好后续Layer计算中所需要的Tensor</span></span><br><span class="line"><span class="comment">   * 如果图是第二次以上运行，则检查输入operand的形状和operand中张量的形状是否匹配</span></span><br><span class="line"><span class="comment">   * @param operators 计算图中的计算节点</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="function"><span class="type">static</span> <span class="type">void</span> <span class="title">InitOperatorInputTensor</span><span class="params">(<span class="type">const</span> std::vector&lt;std::shared_ptr&lt;RuntimeOperator&gt;&gt; &amp;operators)</span></span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 如果图是第一次运行，则根据节点输出operand的形状准备好后续Layer计算中所需要的Tensor</span></span><br><span class="line"><span class="comment">   * 如果图是第二次以上运行，则检查输出operand的形状和operand中张量的形状是否匹配</span></span><br><span class="line"><span class="comment">   * @param pnnx_operators pnnx图节点</span></span><br><span class="line"><span class="comment">   * @param operators KuiperInfer计算图中的计算节点</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="function"><span class="type">static</span> <span class="type">void</span> <span class="title">InitOperatorOutputTensor</span><span class="params">(<span class="type">const</span> std::vector&lt;pnnx::Operator *&gt; &amp;pnnx_operators,</span></span></span><br><span class="line"><span class="params"><span class="function">                                       <span class="type">const</span> std::vector&lt;std::shared_ptr&lt;RuntimeOperator&gt;&gt; &amp;operators)</span></span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">RuntimeGraphShape::InitOperatorInputTensor</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">    <span class="type">const</span> std::vector&lt;std::shared_ptr&lt;RuntimeOperator&gt;&gt; &amp;operators)</span> </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (operators.<span class="built_in">empty</span>()) &#123;</span><br><span class="line">    <span class="built_in">LOG</span>(ERROR) &lt;&lt; <span class="string">&quot;Operators for init input shapes is empty!&quot;</span>;</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">for</span> (<span class="type">const</span> <span class="keyword">auto</span> &amp;op : operators) &#123;</span><br><span class="line">    <span class="comment">// 遍历所有的operators</span></span><br><span class="line">    <span class="keyword">if</span> (op-&gt;input_operands.<span class="built_in">empty</span>()) &#123;</span><br><span class="line">      <span class="keyword">continue</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="type">const</span> std::map&lt;std::string, std::shared_ptr&lt;RuntimeOperand&gt;&gt; &amp;</span><br><span class="line">          input_operands_map = op-&gt;input_operands;</span><br><span class="line">      <span class="keyword">for</span> (<span class="type">const</span> <span class="keyword">auto</span> &amp;input_operand_iter : input_operands_map) &#123;</span><br><span class="line">        <span class="comment">// 遍历该operator对应的input_operands</span></span><br><span class="line">        <span class="type">const</span> <span class="keyword">auto</span> &amp;input_operand = input_operand_iter.second;  <span class="comment">// 键值对中的value</span></span><br><span class="line"></span><br><span class="line">        <span class="type">const</span> <span class="keyword">auto</span> &amp;type = input_operand-&gt;type;</span><br><span class="line">        <span class="built_in">CHECK</span>(type == RuntimeDataType::kTypeFloat32)</span><br><span class="line">                &lt;&lt; <span class="string">&quot;The graph only support float32 yet!&quot;</span>;</span><br><span class="line">        <span class="type">const</span> <span class="keyword">auto</span> &amp;input_operand_shape = input_operand-&gt;shapes;</span><br><span class="line">        <span class="keyword">auto</span> &amp;input_datas = input_operand-&gt;datas;</span><br><span class="line"></span><br><span class="line">        <span class="built_in">CHECK</span>(!input_operand_shape.<span class="built_in">empty</span>());</span><br><span class="line">        <span class="type">const</span> <span class="type">int32_t</span> batch = input_operand_shape.<span class="built_in">at</span>(<span class="number">0</span>);  <span class="comment">// 得到批次大小</span></span><br><span class="line">        <span class="built_in">CHECK</span>(batch &gt;= <span class="number">0</span>) &lt;&lt; <span class="string">&quot;Dynamic batch size is not supported!&quot;</span>;</span><br><span class="line">        <span class="built_in">CHECK</span>(input_operand_shape.<span class="built_in">size</span>() == <span class="number">2</span> ||</span><br><span class="line">            input_operand_shape.<span class="built_in">size</span>() == <span class="number">4</span> ||</span><br><span class="line">            input_operand_shape.<span class="built_in">size</span>() == <span class="number">3</span>)</span><br><span class="line">                &lt;&lt; <span class="string">&quot;Unsupported tensor shape sizes: &quot;</span> &lt;&lt; input_operand_shape.<span class="built_in">size</span>();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (!input_datas.<span class="built_in">empty</span>()) &#123;</span><br><span class="line">          <span class="comment">// 如果数据非空</span></span><br><span class="line">          <span class="built_in">CHECK</span>(input_datas.<span class="built_in">size</span>() == batch) &lt;&lt; <span class="string">&quot;Batch size is wrong!&quot;</span>;</span><br><span class="line">          <span class="keyword">for</span> (<span class="type">int32_t</span> i = <span class="number">0</span>; i &lt; batch; ++i) &#123;</span><br><span class="line">            <span class="comment">// 遍历所有批次，做形状检查，避免第二次的初始化</span></span><br><span class="line">            <span class="type">const</span> std::vector&lt;<span class="type">uint32_t</span>&gt; &amp;input_data_shape =</span><br><span class="line">                input_datas.<span class="built_in">at</span>(i)-&gt;<span class="built_in">shapes</span>();</span><br><span class="line">            <span class="built_in">CHECK</span>(input_data_shape.<span class="built_in">size</span>() == <span class="number">3</span>)</span><br><span class="line">                    &lt;&lt; <span class="string">&quot;THe origin shape size of operator input data do not equals &quot;</span></span><br><span class="line">                       <span class="string">&quot;to three&quot;</span>;</span><br><span class="line">            <span class="keyword">if</span> (input_operand_shape.<span class="built_in">size</span>() == <span class="number">4</span>) &#123;</span><br><span class="line">              <span class="built_in">CHECK</span>(input_data_shape.<span class="built_in">at</span>(<span class="number">0</span>) == input_operand_shape.<span class="built_in">at</span>(<span class="number">1</span>) &amp;&amp;</span><br><span class="line">                  input_data_shape.<span class="built_in">at</span>(<span class="number">1</span>) == input_operand_shape.<span class="built_in">at</span>(<span class="number">2</span>) &amp;&amp;</span><br><span class="line">                  input_data_shape.<span class="built_in">at</span>(<span class="number">2</span>) == input_operand_shape.<span class="built_in">at</span>(<span class="number">3</span>));</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (input_operand_shape.<span class="built_in">size</span>() == <span class="number">2</span>) &#123;</span><br><span class="line">              <span class="built_in">CHECK</span>(input_data_shape.<span class="built_in">at</span>(<span class="number">1</span>) == input_operand_shape.<span class="built_in">at</span>(<span class="number">1</span>) &amp;&amp;</span><br><span class="line">                  input_data_shape.<span class="built_in">at</span>(<span class="number">0</span>) == <span class="number">1</span> &amp;&amp; input_data_shape.<span class="built_in">at</span>(<span class="number">2</span>) == <span class="number">1</span>);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">              <span class="comment">// current shape size = 3</span></span><br><span class="line">              <span class="built_in">CHECK</span>(input_data_shape.<span class="built_in">at</span>(<span class="number">1</span>) == input_operand_shape.<span class="built_in">at</span>(<span class="number">1</span>) &amp;&amp;</span><br><span class="line">                  input_data_shape.<span class="built_in">at</span>(<span class="number">0</span>) == <span class="number">1</span> &amp;&amp;</span><br><span class="line">                  input_data_shape.<span class="built_in">at</span>(<span class="number">2</span>) == input_operand_shape.<span class="built_in">at</span>(<span class="number">2</span>));</span><br><span class="line">            &#125;</span><br><span class="line">          &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          <span class="comment">// 输入数据是空的</span></span><br><span class="line">          input_datas.<span class="built_in">resize</span>(batch);</span><br><span class="line">          <span class="keyword">for</span> (<span class="type">int32_t</span> i = <span class="number">0</span>; i &lt; batch; ++i) &#123;</span><br><span class="line">            <span class="comment">// 遍历所有批次，初始化张量</span></span><br><span class="line">            <span class="keyword">if</span> (input_operand_shape.<span class="built_in">size</span>() == <span class="number">4</span>) &#123;</span><br><span class="line">              input_datas.<span class="built_in">at</span>(i) = std::make_shared&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;(</span><br><span class="line">                  input_operand_shape.<span class="built_in">at</span>(<span class="number">1</span>), input_operand_shape.<span class="built_in">at</span>(<span class="number">2</span>),</span><br><span class="line">                  input_operand_shape.<span class="built_in">at</span>(<span class="number">3</span>));</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (input_operand_shape.<span class="built_in">size</span>() == <span class="number">2</span>) &#123;</span><br><span class="line">              input_datas.<span class="built_in">at</span>(i) = std::make_shared&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;(</span><br><span class="line">                  <span class="number">1</span>, input_operand_shape.<span class="built_in">at</span>(<span class="number">1</span>), <span class="number">1</span>);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">              <span class="comment">// current shape is 3</span></span><br><span class="line">              input_datas.<span class="built_in">at</span>(i) = std::make_shared&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;(</span><br><span class="line">                  <span class="number">1</span>, input_operand_shape.<span class="built_in">at</span>(<span class="number">1</span>), input_operand_shape.<span class="built_in">at</span>(<span class="number">2</span>));</span><br><span class="line">            &#125;</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">RuntimeGraphShape::InitOperatorOutputTensor</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">    <span class="type">const</span> std::vector&lt;pnnx::Operator *&gt; &amp;pnnx_operators,</span></span></span><br><span class="line"><span class="params"><span class="function">    <span class="type">const</span> std::vector&lt;std::shared_ptr&lt;RuntimeOperator&gt;&gt; &amp;operators)</span> </span>&#123;</span><br><span class="line">  <span class="built_in">CHECK</span>(!pnnx_operators.<span class="built_in">empty</span>() &amp;&amp; !operators.<span class="built_in">empty</span>());</span><br><span class="line">  <span class="built_in">CHECK</span>(pnnx_operators.<span class="built_in">size</span>() == operators.<span class="built_in">size</span>());</span><br><span class="line">  <span class="keyword">for</span> (<span class="type">uint32_t</span> i = <span class="number">0</span>; i &lt; pnnx_operators.<span class="built_in">size</span>(); ++i) &#123;</span><br><span class="line">    <span class="comment">// 遍历所有的pnnx_operators</span></span><br><span class="line">    <span class="type">const</span> std::vector&lt;pnnx::Operand *&gt; operands = pnnx_operators.<span class="built_in">at</span>(i)-&gt;outputs;</span><br><span class="line">    <span class="built_in">CHECK</span>(operands.<span class="built_in">size</span>() &lt;= <span class="number">1</span>) &lt;&lt; <span class="string">&quot;Only support one node one output yet!&quot;</span>;</span><br><span class="line">    <span class="keyword">if</span> (operands.<span class="built_in">empty</span>()) &#123;</span><br><span class="line">      <span class="keyword">continue</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 如果operands的非空的</span></span><br><span class="line">    <span class="built_in">CHECK</span>(operands.<span class="built_in">size</span>() == <span class="number">1</span>) &lt;&lt; <span class="string">&quot;Only support one output in the KuiperInfer&quot;</span>;</span><br><span class="line">    pnnx::Operand *operand = operands.<span class="built_in">front</span>();</span><br><span class="line">    <span class="type">const</span> <span class="keyword">auto</span> &amp;runtime_op = operators.<span class="built_in">at</span>(i);</span><br><span class="line">    <span class="built_in">CHECK</span>(operand != <span class="literal">nullptr</span>) &lt;&lt; <span class="string">&quot;Operand output is null&quot;</span>;</span><br><span class="line">    <span class="type">const</span> std::vector&lt;<span class="type">int32_t</span>&gt; &amp;operand_shapes = operand-&gt;shape;</span><br><span class="line">    <span class="type">const</span> <span class="keyword">auto</span> &amp;output_tensors = runtime_op-&gt;output_operands;</span><br><span class="line"></span><br><span class="line">    <span class="type">const</span> <span class="type">int32_t</span> batch = operand_shapes.<span class="built_in">at</span>(<span class="number">0</span>);</span><br><span class="line">    <span class="built_in">CHECK</span>(batch &gt;= <span class="number">0</span>) &lt;&lt; <span class="string">&quot;Dynamic batch size is not supported!&quot;</span>;</span><br><span class="line">    <span class="built_in">CHECK</span>(operand_shapes.<span class="built_in">size</span>() == <span class="number">2</span> || operand_shapes.<span class="built_in">size</span>() == <span class="number">4</span> ||</span><br><span class="line">        operand_shapes.<span class="built_in">size</span>() == <span class="number">3</span>)</span><br><span class="line">            &lt;&lt; <span class="string">&quot;Unsupported shape sizes: &quot;</span> &lt;&lt; operand_shapes.<span class="built_in">size</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!output_tensors) &#123;</span><br><span class="line">      <span class="comment">// 如果output_operands是空的，初始化输出张量</span></span><br><span class="line">      std::shared_ptr&lt;RuntimeOperand&gt; output_operand =</span><br><span class="line">          std::<span class="built_in">make_shared</span>&lt;RuntimeOperand&gt;();</span><br><span class="line">      output_operand-&gt;shapes = operand_shapes;</span><br><span class="line">      output_operand-&gt;type = RuntimeDataType::kTypeFloat32;</span><br><span class="line">      output_operand-&gt;name = operand-&gt;name + <span class="string">&quot;_output&quot;</span>;</span><br><span class="line">      <span class="keyword">for</span> (<span class="type">int</span> j = <span class="number">0</span>; j &lt; batch; ++j) &#123;</span><br><span class="line">        <span class="comment">// 遍历每一批次的数据，放到output_operand</span></span><br><span class="line">        <span class="keyword">if</span> (operand_shapes.<span class="built_in">size</span>() == <span class="number">4</span>) &#123;</span><br><span class="line">          output_operand-&gt;datas.<span class="built_in">push_back</span>(std::make_shared&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;(</span><br><span class="line">              operand_shapes.<span class="built_in">at</span>(<span class="number">1</span>), operand_shapes.<span class="built_in">at</span>(<span class="number">2</span>),</span><br><span class="line">              operand_shapes.<span class="built_in">at</span>(<span class="number">3</span>)));</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (operand_shapes.<span class="built_in">size</span>() == <span class="number">2</span>) &#123;</span><br><span class="line">          output_operand-&gt;datas.<span class="built_in">push_back</span>(</span><br><span class="line">              std::make_shared&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;(<span class="number">1</span>, operand_shapes.<span class="built_in">at</span>(<span class="number">1</span>), <span class="number">1</span>));</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          <span class="comment">// current shape is 3</span></span><br><span class="line">          output_operand-&gt;datas.<span class="built_in">push_back</span>(std::make_shared&lt;Tensor&lt;<span class="type">float</span>&gt;&gt;(</span><br><span class="line">              <span class="number">1</span>, operand_shapes.<span class="built_in">at</span>(<span class="number">1</span>), operand_shapes.<span class="built_in">at</span>(<span class="number">2</span>)));</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      runtime_op-&gt;output_operands = std::<span class="built_in">move</span>(output_operand);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// 如果output_operands是非空的</span></span><br><span class="line">      <span class="built_in">CHECK</span>(batch == output_tensors-&gt;datas.<span class="built_in">size</span>());</span><br><span class="line">      <span class="comment">// output_tensors empty</span></span><br><span class="line">      <span class="built_in">CHECK</span>(output_tensors-&gt;type == RuntimeDataType::kTypeFloat32);</span><br><span class="line">      <span class="built_in">CHECK</span>(output_tensors-&gt;shapes == operand_shapes);</span><br><span class="line">      <span class="keyword">for</span> (<span class="type">uint32_t</span> b = <span class="number">0</span>; b &lt; batch; ++b) &#123;</span><br><span class="line">        <span class="comment">// 遍历每一批次的数据，做形状检查，如果形状不对，则reshape</span></span><br><span class="line">        <span class="type">const</span> std::vector&lt;<span class="type">uint32_t</span>&gt; &amp;tensor_shapes =</span><br><span class="line">            output_tensors-&gt;datas.<span class="built_in">at</span>(b)-&gt;<span class="built_in">shapes</span>();</span><br><span class="line">        <span class="keyword">if</span> (operand_shapes.<span class="built_in">size</span>() == <span class="number">4</span>) &#123;</span><br><span class="line">          <span class="keyword">if</span> (tensor_shapes.<span class="built_in">at</span>(<span class="number">0</span>) != operand_shapes.<span class="built_in">at</span>(<span class="number">1</span>) ||</span><br><span class="line">              tensor_shapes.<span class="built_in">at</span>(<span class="number">1</span>) != operand_shapes.<span class="built_in">at</span>(<span class="number">2</span>) ||</span><br><span class="line">              tensor_shapes.<span class="built_in">at</span>(<span class="number">2</span>) != operand_shapes.<span class="built_in">at</span>(<span class="number">3</span>)) &#123;</span><br><span class="line">            <span class="built_in">DLOG</span>(WARNING) &lt;&lt; <span class="string">&quot;The shape of tensor do not adapting with output operand&quot;</span>;</span><br><span class="line">            <span class="type">const</span> <span class="keyword">auto</span> &amp;target_shapes = std::vector&lt;<span class="type">uint32_t</span>&gt;&#123;(<span class="type">uint32_t</span>) operand_shapes.<span class="built_in">at</span>(<span class="number">1</span>),</span><br><span class="line">                                                              (<span class="type">uint32_t</span>) operand_shapes.<span class="built_in">at</span>(<span class="number">2</span>),</span><br><span class="line">                                                              (<span class="type">uint32_t</span>) operand_shapes.<span class="built_in">at</span>(<span class="number">3</span>)&#125;;</span><br><span class="line">            output_tensors-&gt;datas.<span class="built_in">at</span>(b)-&gt;<span class="built_in">ReRawshape</span>(target_shapes);</span><br><span class="line">          &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (operand_shapes.<span class="built_in">size</span>() == <span class="number">2</span>) &#123;</span><br><span class="line">          <span class="keyword">if</span> (tensor_shapes.<span class="built_in">at</span>(<span class="number">0</span>) != <span class="number">1</span> ||</span><br><span class="line">              tensor_shapes.<span class="built_in">at</span>(<span class="number">1</span>) != operand_shapes.<span class="built_in">at</span>(<span class="number">1</span>) ||</span><br><span class="line">              tensor_shapes.<span class="built_in">at</span>(<span class="number">2</span>) != <span class="number">1</span>) &#123;</span><br><span class="line">            <span class="built_in">DLOG</span>(WARNING) &lt;&lt; <span class="string">&quot;The shape of tensor do not adapting with output operand&quot;</span>;</span><br><span class="line">            <span class="type">const</span> <span class="keyword">auto</span> &amp;target_shapes = std::vector&lt;<span class="type">uint32_t</span>&gt;&#123;<span class="number">1</span>, (<span class="type">uint32_t</span>) operand_shapes.<span class="built_in">at</span>(<span class="number">1</span>), <span class="number">1</span>&#125;;</span><br><span class="line">            output_tensors-&gt;datas.<span class="built_in">at</span>(b)-&gt;<span class="built_in">ReRawshape</span>(target_shapes);</span><br><span class="line">          &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          <span class="comment">// current shape is 3</span></span><br><span class="line">          <span class="keyword">if</span> (tensor_shapes.<span class="built_in">at</span>(<span class="number">0</span>) != <span class="number">1</span> ||</span><br><span class="line">              tensor_shapes.<span class="built_in">at</span>(<span class="number">1</span>) != operand_shapes.<span class="built_in">at</span>(<span class="number">1</span>) ||</span><br><span class="line">              tensor_shapes.<span class="built_in">at</span>(<span class="number">2</span>) != operand_shapes.<span class="built_in">at</span>(<span class="number">2</span>)) &#123;</span><br><span class="line">            <span class="built_in">DLOG</span>(WARNING) &lt;&lt; <span class="string">&quot;The shape of tensor do not adapting with output operand&quot;</span>;</span><br><span class="line">            <span class="type">const</span> <span class="keyword">auto</span> &amp;target_shapes =</span><br><span class="line">                std::vector&lt;<span class="type">uint32_t</span>&gt;&#123;<span class="number">1</span>, (<span class="type">uint32_t</span>) operand_shapes.<span class="built_in">at</span>(<span class="number">1</span>), (<span class="type">uint32_t</span>) operand_shapes.<span class="built_in">at</span>(<span class="number">2</span>)&#125;;</span><br><span class="line">            output_tensors-&gt;datas.<span class="built_in">at</span>(b)-&gt;<span class="built_in">ReRawshape</span>(target_shapes);</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://kilogrand.gitee.io">kiloGrand</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://kilogrand.gitee.io/2023/03/21/kuiper_infer-L11/">https://kilogrand.gitee.io/2023/03/21/kuiper_infer-L11/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://kilogrand.gitee.io" target="_blank">kiloGrand</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/kuiper-infer/">kuiper_infer</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/03/20/kuiper_infer-L10/"><img class="prev-cover" src="/img/coding.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">自制深度学习框架--Im2Col原理与卷积层的实现</div></div></a></div><div class="next-post pull-right"><a href="/2023/03/22/kuiper_infer-L12/"><img class="next-cover" src="/img/coding.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">自制深度学习框架--算子的执行流程</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2023/03/20/kuiper_infer-L10/" title="自制深度学习框架--Im2Col原理与卷积层的实现"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-20</div><div class="title">自制深度学习框架--Im2Col原理与卷积层的实现</div></div></a></div><div><a href="/2023/03/24/kuiper_infer-L14/" title="自制深度学习框架--实现Yolov5的推理"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-24</div><div class="title">自制深度学习框架--实现Yolov5的推理</div></div></a></div><div><a href="/2023/03/22/kuiper_infer-L12/" title="自制深度学习框架--算子的执行流程"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-22</div><div class="title">自制深度学习框架--算子的执行流程</div></div></a></div><div><a href="/2023/03/23/kuiper_infer-L13/" title="自制深度学习框架--实现ResNet网络的推理"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-23</div><div class="title">自制深度学习框架--实现ResNet网络的推理</div></div></a></div><div><a href="/2023/03/14/kuiper_infer-L3/" title="自制深度学习框架--导入数据"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-14</div><div class="title">自制深度学习框架--导入数据</div></div></a></div><div><a href="/2023/03/13/kuiper_infer-L2/" title="自制深度学习框架--张量"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-13</div><div class="title">自制深度学习框架--张量</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/profile.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">kiloGrand</div><div class="author-info__description">coder && data-science researcher</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/kiloGrand/"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%86%8D%E6%8E%A2Tensor%E7%B1%BB"><span class="toc-number">1.</span> <span class="toc-text">再探Tensor类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%97%E4%BC%98%E5%85%88%E7%9A%84Reshape"><span class="toc-number">1.1.</span> <span class="toc-text">列优先的Reshape</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A1%8C%E4%BC%98%E5%85%88%E7%9A%84Reshape"><span class="toc-number">1.2.</span> <span class="toc-text">行优先的Reshape</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%9E%84%E5%BB%BA%E8%AE%A1%E7%AE%97%E5%9B%BE%E7%9A%84%E5%9B%BE%E5%85%B3%E7%B3%BB"><span class="toc-number">2.</span> <span class="toc-text">构建计算图的图关系</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%9D%E5%A7%8B%E5%8C%96%E5%90%84%E7%AE%97%E5%AD%90%E7%9A%84%E8%BE%93%E5%85%A5%E5%92%8C%E8%BE%93%E5%87%BA%E7%A9%BA%E9%97%B4"><span class="toc-number">3.</span> <span class="toc-text">初始化各算子的输入和输出空间</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/24/kuiper_infer-L14/" title="自制深度学习框架--实现Yolov5的推理">自制深度学习框架--实现Yolov5的推理</a><time datetime="2023-03-24T12:00:00.000Z" title="发表于 2023-03-24 20:00:00">2023-03-24</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/23/kuiper_infer-L13/" title="自制深度学习框架--实现ResNet网络的推理">自制深度学习框架--实现ResNet网络的推理</a><time datetime="2023-03-23T12:00:00.000Z" title="发表于 2023-03-23 20:00:00">2023-03-23</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/22/kuiper_infer-L12/" title="自制深度学习框架--算子的执行流程">自制深度学习框架--算子的执行流程</a><time datetime="2023-03-22T12:00:00.000Z" title="发表于 2023-03-22 20:00:00">2023-03-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/21/kuiper_infer-L11/" title="自制深度学习框架--再探Tensor类并构建计算图的图关系">自制深度学习框架--再探Tensor类并构建计算图的图关系</a><time datetime="2023-03-21T12:00:00.000Z" title="发表于 2023-03-21 20:00:00">2023-03-21</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/20/kuiper_infer-L10/" title="自制深度学习框架--Im2Col原理与卷积层的实现">自制深度学习框架--Im2Col原理与卷积层的实现</a><time datetime="2023-03-20T12:00:00.000Z" title="发表于 2023-03-20 20:00:00">2023-03-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 - 2023 By kiloGrand</div><div class="footer_custom_text">Hi, welcome to my blog!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>